#include "DatabaseManager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

DatabaseManager& DatabaseManager::instance()
{
    static DatabaseManager instance;
    return instance;
}

DatabaseManager::DatabaseManager() {}

bool DatabaseManager::initDatabase(const QString& dbPath)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);
    if (!db.open()) {
        qDebug() << "数据库打开失败:" << db.lastError().text();
        return false;
    }

    QSqlQuery query;
    bool ok = query.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, avatar TEXT)")
           && query.exec("CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type INTEGER)")
           && query.exec("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id INTEGER, sender_id INTEGER, content TEXT, time TEXT, type INTEGER)");
    if (!ok) {
        qDebug() << "建表失败:" << query.lastError().text();
    }
    return ok;
}

bool DatabaseManager::insertUser(const QString& name, const QString& avatar)
{
    QSqlQuery query;
    query.prepare("INSERT INTO users (name, avatar) VALUES (?, ?)");
    query.addBindValue(name);
    query.addBindValue(avatar);
    if (!query.exec()) {
        qDebug() << "插入用户失败:" << query.lastError().text();
        return false;
    }
    return true;
}

bool DatabaseManager::insertMessage(int sessionId, int senderId, const QString& content, const QString& time, int type)
{
    QSqlQuery query;
    query.prepare("INSERT INTO messages (session_id, sender_id, content, time, type) VALUES (?, ?, ?, ?, ?)");
    query.addBindValue(sessionId);
    query.addBindValue(senderId);
    query.addBindValue(content);
    query.addBindValue(time);
    query.addBindValue(type);
    if (!query.exec()) {
        qDebug() << "插入消息失败:" << query.lastError().text();
        return false;
    }
    return true;
}

QVariantList DatabaseManager::queryAllUsers()
{
    QVariantList users;
    QSqlQuery query("SELECT id, name, avatar FROM users");
    while (query.next()) {
        QVariantMap user;
        user["id"] = query.value(0);
        user["name"] = query.value(1);
        user["avatar"] = query.value(2);
        users << user;
    }
    return users;
}

QVariantList DatabaseManager::queryMessagesBySession(int sessionId)
{
    QVariantList messages;
    QSqlQuery query;
    query.prepare("SELECT sender_id, content, time, type FROM messages WHERE session_id=? ORDER BY time ASC");
    query.addBindValue(sessionId);
    query.exec();
    while (query.next()) {
        QVariantMap msg;
        msg["sender_id"] = query.value(0);
        msg["content"] = query.value(1);
        msg["time"] = query.value(2);
        msg["type"] = query.value(3);
        messages << msg;
    }
    return messages;
}

bool DatabaseManager::updateUserName(int userId, const QString& newName)
{
    QSqlQuery query;
    query.prepare("UPDATE users SET name=? WHERE id=?");
    query.addBindValue(newName);
    query.addBindValue(userId);
    if (!query.exec()) {
        qDebug() << "更新用户失败:" << query.lastError().text();
        return false;
    }
    return true;
}

bool DatabaseManager::deleteMessage(int msgId)
{
    QSqlQuery query;
    query.prepare("DELETE FROM messages WHERE id=?");
    query.addBindValue(msgId);
    if (!query.exec()) {
        qDebug() << "删除消息失败:" << query.lastError().text();
        return false;
    }
    return true;
}